package com.fangcun.common.util.base;

import java.math.BigDecimal;

import org.springframework.beans.factory.annotation.Autowired;

import com.fangcun.bean.admin.agent.response.AgentShareBenefitsRuleDetail;
import com.fangcun.bean.api.agent.goods.ProfitCalculation;
import com.fangcun.common.canstant.PublicConstant;
import com.fangcun.common.exception.ProException;
import com.fangcun.common.exception.ProValiDataException;
import com.fangcun.common.redis.RedisService;
import com.fangcun.entity.AgentShareBenefitsRule;

/**
 * @作者： 陳曉鬆 @时间： 2020年4月26日 - 下午6:01:00 @description：->
 */
public class BaseService {

	@Autowired
	protected RedisService redisService;

	/**
	 * @作者：陳曉鬆 @时间：2020年8月20日 下午3:35:33 @版本：V1.0 @description：-> 计算分润金额
	 */
	protected ProfitCalculation calculationProfit(AgentShareBenefitsRuleDetail share, BigDecimal price) throws ProException {
		BigDecimal profitPrice = null;
		boolean isParent = false;
		if (share.getParentAgentShareBenefits() != null) {
			AgentShareBenefitsRule parentAgentShareBenefits = share.getParentAgentShareBenefits();
			BigDecimal parentProfitPrice = null;
			if (PublicConstant.SHARE_TYPE_1 == parentAgentShareBenefits.getShareType() && parentAgentShareBenefits.getNumericalValue().doubleValue() > 0
					&& parentAgentShareBenefits.getNumericalValue().doubleValue() < 1) {
				parentProfitPrice = price.multiply(parentAgentShareBenefits.getNumericalValue());
			}
			if (PublicConstant.SHARE_TYPE_2 == parentAgentShareBenefits.getShareType() && parentAgentShareBenefits.getNumericalValue().doubleValue() > 0) {
				parentProfitPrice = parentAgentShareBenefits.getNumericalValue();
			}
			if (parentProfitPrice == null) {
				throw new ProValiDataException("父级代理商没有利润");
			}
			price = parentProfitPrice;
			isParent = true;
		}
		price = price.setScale(2, BigDecimal.ROUND_HALF_UP);
		if (PublicConstant.SHARE_TYPE_1 == share.getShareType() && share.getNumericalValue().doubleValue() > 0 && share.getNumericalValue().doubleValue() < 1) {
			profitPrice = price.multiply(share.getNumericalValue());
		}
		if (PublicConstant.SHARE_TYPE_2 == share.getShareType() && share.getNumericalValue().doubleValue() > 0) {
			profitPrice = share.getNumericalValue();
		}
		if (profitPrice == null) {
			throw new ProValiDataException("代理商没有利润");
		}
		ProfitCalculation p = new ProfitCalculation();
		p.setProfitPrice(profitPrice.setScale(2, BigDecimal.ROUND_HALF_UP));
		p.setParentProfitPrice(isParent ? price.subtract(p.getProfitPrice()) : BigDecimal.valueOf(0));
		return p;
	}

}
